﻿using System;
using System.Net.Mail;
using Logger = KC.Logging.Logger;
using C = KC.Overhead.Constants;

namespace KC.Business.Net
{
	public static class Mail
	{
		/// <summary>Sends mail.</summary>
		/// <param name="to">Who to send to</param>
		/// <param name="subject">Mail subject</param>
		/// <param name="body">Text body of message</param>
		public static void SendMail(string to, string subject, string body)
		{
			// Validate params
			if (string.IsNullOrEmpty(to)) throw new ArgumentNullException("to");
			if (string.IsNullOrEmpty(subject)) throw new ArgumentNullException("subject");
			if (string.IsNullOrEmpty(body)) throw new ArgumentNullException("body");

			// Get & Validate config keys
			string
				from = C.Net.Mail.From,
				MailServer = C.Net.Mail.Server,
				MailPass = C.Net.Mail.Pass;
			if (string.IsNullOrEmpty(from)) throw new MissingFieldException("Config key MailUser missing");
			if (string.IsNullOrEmpty(MailServer)) throw new MissingFieldException("Config key MailServer missing");
			if (string.IsNullOrEmpty(MailPass)) throw new MissingFieldException("Config key MailPass missing");

			// Send mail
			using (MailMessage myMessage = new MailMessage(from, to, subject, body))
				using (SmtpClient myClient = new SmtpClient(MailServer)) {
					myClient.UseDefaultCredentials = false;
					myClient.Credentials = new System.Net.NetworkCredential(from, MailPass);
					myClient.DeliveryMethod = SmtpDeliveryMethod.Network;
					try { myClient.Send(myMessage); }
					catch (SmtpException ex) { Logger.LogError(Logger.Project.KcArchitecture, Logger.ErrorLevel.Warning, ex.ToString()); }
					catch (Exception ex) { Logger.LogError(Logger.Project.KcArchitecture, Logger.ErrorLevel.Error, ex.ToString()); }  }
		}
	}
}
